<?php
/**
 * @Author: Marte
 * @Date:   2020-01-16 09:50:05
 * @Last Modified by:   Marte
 * @Last Modified time: 2020-01-16 10:58:45
 */
use Firebase\JWT\ExpiredException;
use Firebase\JWT\JWT;
use Firebase\JWT\SignatureInvalidException;

// composer require firebase/php-jwt
class Sign{
    protected $key = 'hello123456';
    protected $algs = ['HS256'];

    public function  issue(){
        $time=time();
        $token = array(
            "iss" => "http://test.com",    //签发者,可选
            "aud" => "http://test.cn",     //接收者,可选
            "iat" =>$time, //签发时间
            "nbf" => $time, //生效时间
            "exp" => $time+7200, //过期时间
            'data'=>[
                'uid'=>1,
                'name'=>'hello'
            ]
        );
        return \Firebase\JWT\JWT::encode($token, $this->key);
    }

    public function check($token){
        try{
            $result = JWT::decode($token, $this->key, $this->algs);
            return $result->data;
        }catch (SignatureInvalidException $e) {  //签名错误
            return $e->getMessage();
        }catch (ExpiredException $e){  //token过期
            return $e->getMessage();
        }catch (Exception $e){
            return $e->getMessage();
        }
    }
}

$jwt = new Sign();
$token = $jwt->issue();
var_dump($token);

$check = $jwt->check($token);
var_dump($check);